$(function (){
    $("#wuliao").hide()
    $("#tableinfo").bootstrapTable({
        method:'post',
        //请求头部设置
        contentType:'application/json',
        url:'/TYMDfile/selbywuliao',
        //设置交替样式
        striped: true,
        //初始显示页号
        pageNumber:1,
        //设置表格高度
        //height:350,
        //是否显示分页
        pagination:true,
        //设置是服务端分页还是客户端分页
        sidePagination:'server',
        //每页显示条数
        pageSize:5,
        //可选每页显示数量
        pageList:[2,3,4,5],
        //上传到服务段的参数
        queryParams:function (params) {
            return{
                //计算页号（当前页）
                pageNum: (params.offset / params.limit) + 1,
                pageSize:params.limit
            };
        },
        columns:[
            {title:"产品编号" , field:"productId" , align:'center'},
            {title:"产品名称" , field:"productName" , align:'center'},
            {title:"用途类型" , field:"type" , align:'center',
                formatter:function (value,row,index) {
                        if(value==1){
                            return "产品";
                        }else {
                            return "物料";
                        }
                }},
            {title:"I级分类" , field:"firstKindName" , align:'center'},
            {title:"II级分类" , field:"secondKindName" , align:'center'},
            {title:"III级分类" , field:"thirdKindName" , align:'center'},
            {title:"产品经理" , field:"responsiblePers" , align:'center',
                formatter:function (value,row,index) {
                    if(value==null){return "";}else {return value;}
                }
            },
            {title: "制定",field:"fileId",align: 'center',
                formatter:function (value,row,index) {
                    var btn1 = "<button type='button' class='btn btn-info' onclick='shows("+value+")'>制定物料计划表</button>";
                    return btn1;
                }
            }]
    })
})

function shows(a) {
    $("#table").hide();
    $("#wuliao").show();
    $("#register").val(parent.document.getElementsByClassName("user_name")[0].innerHTML);
    $("#sheji").val(parent.document.getElementsByClassName("user_name")[0].innerHTML);
    $.ajax({
        url:"/TYMDfile/"+a,
        type:"post",
        contentType:"application/json;charset=utf-8",
        dataType:"json",
        success:function (data) {
            $("#productId").val(data.productId);
            $("#productName").val(data.productName);
        }
    })
}

//查询已通过审核的产品
let dFileList=[];
let arr=[];
function getMApply() {
    $.ajax({
        url:"/TYMDfile/selwuliao",
        type:"post",
        dataType:"json",
        success:function (data) {
            dFileList=data;
            let tr = "";
            for (let i = 0; i < data.length; i++) {
                var amountUnit=data[i].amoutUnil;
                if(amountUnit==undefined){
                    amountUnit="";
                }
                tr+="<tr>\n" +
                    "                    <td>"+data[i].productName+"</td>\n" +
                    "                    <td>"+data[i].productId+"</td>\n" +
                    "                    <td>"+amountUnit+"</td>\n" +
                    "                    <td>"+data[i].costPrice+"</td>\n" +
                    "                    <td><button onclick='addInTable("+i+")'>添加</button></td>\n" +
                    "                </tr>";

            }
            //添加到表格
            $("#moduleWatch").html(tr);
        }
    })
}

//添加产品的方法
function addInTable(index){
    let flag=true;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] == index){
            flag=false;
        }
    }
    if (flag){
        arr.push(index+'');
        let dFileListElement = dFileList[index];
        $("#tbody").append("<tr>\n" +
            "                <td hidden='hidden'><input value='"+dFileListElement.fileId+"' readonly type=\"text\" name=\"fileId\"></td>\n" +
            "                <td><input value='"+dFileListElement.productName+"' readonly type=\"text\" name=\"productName\"></td>\n" +
            "                <td><input value='"+dFileListElement.productId+"' readonly type=\"text\" name=\"productId\"></td>\n" +
            "                <td><input value='"+dFileListElement.productDescribe+"' readonly type=\"text\" name=\"productDescribe\"></td>\n" +
            "                <td><input type=\"number\" min='1' name=\"amount\" value=\"1\" onchange='changeAmount(this,"+dFileListElement.realCostPrice+")'></td>\n" +
            "                <td>"+dFileListElement.amoutUnil+"</td>\n" +
            "                <td class=\"danjia\">"+dFileListElement.realCostPrice+"</td>\n" +
            "                <td class=\"xiaoji\">"+dFileListElement.realCostPrice+"</td>\n" +
            "                <td><button type='button' class='btn btn-primary' onclick='delwuliao("+index+")' id='"+index+"'>删除</button></td>\n" +
            "            </tr>");

        //置空总金额和总数量
        $("#totalCount").html("");
        $("#totalPrice").html("");
        $("#btn-save").hide();
    }

    for (var i = 0; i <arr.length ; i++) {
        console.log("arr里有"+arr[i]);
    }
}

//改变数量
function changeAmount(that,price){
    let amount = $(that).val();
    $(that).parent().next().next().next().html(amount*price);

    //置空总金额和总数量
    $("#totalCount").html("");
    $("#totalPrice").html("");
    $("#btn-save").hide();
}

//点击预览
function preview(){
    if($("#deptId").val() != 0) {
        if($("#tbody").html().trim() != "") {
            //获取数量和小计
            let xiaoji = $(".xiaoji");
            let amounts = $("input[name='amount']");

            //定义总数量和总金额
            let totalCount = 0;
            let totalPrice = 0;
            amounts.each(function (i, e) {
                totalCount += parseInt($(e).val());
            })
            xiaoji.each(function (i, e) {
                totalPrice += parseFloat($(e).html());
            })

            $("#totalCount").html(totalCount);
            $("#totalPrice").html(totalPrice);
            $("#btn-save").show();
        } else {
            alert("添加物料后才能预览");
        }
    }else {
        alert("请选择审核部门");
    }

}


function delwuliao(a){
    var number;
    for (var i = 0; i <arr.length ; i++) {
        number = arr.indexOf(a+'');
    }
            arr.splice(number, 1);
            $("#"+a).parent().parent().remove();
    //置空总金额和总数量
    $("#totalCount").html("");
    $("#totalPrice").html("");
    $("#btn-save").hide();
}

//提交生产计划单
function savebywuliao(){

    var dmodule = {
        productName : $("#productName").val(),
        productId : $("#productId").val(),
        deptId :1,
        moduleDescribe : $("#remark").val(),
        costPriceSum : $("#totalPrice").html(),
    }
    //获取四个input框
    let productNames = $("input[name='productName']");
    let productIds = $("input[name='productId']");
    let productDescribes = $("input[name='productDescribe']");
    let amounts = $("input[name='amount']");
    let danjia = $("td[class='danjia']");
    let xiaoji = $("td[class='xiaoji']");
    let fileId = $("input[name='fileId']");

    //定义数组存值
    let mApplyArray=[];
    productIds.each(function (i,e){
        let mApply={
            detailsNumber:fileId[i].value,
            productName:productNames[i].value,
            productId:productIds[i].value,
            productDescribe:productDescribes[i].value,
            amount:amounts[i].value,
            costPrice:danjia[i].innerHTML,
            subtotal:xiaoji[i].innerHTML
        }
        //加入数组
        mApplyArray[i]=mApply;

    })
    dmodule.dList = mApplyArray;
    $.ajax({
        url: "/TYMDes/insert",
        type: "post",
        contentType:"application/json;charset=utf-8",
        data:JSON.stringify(dmodule),
        success:function (data){
            if(data>0){
                alert("添加成功");
            }else {
                alert("添加失败");
            }
            $("#table").show();
            $("#wuliao").hide();
            $("#tableinfo").bootstrapTable("refresh");
        }
    })
}
